package com.atguigu.auth.service.impl;
import com.atguigu.auth.mapper.SysRoleMapper;
import com.atguigu.auth.service.SysRoleService;
import com.atguigu.auth.service.SysUserRoleService;
import com.atguigu.model.system.SysRole;
import com.atguigu.model.system.SysUser;
import com.atguigu.model.system.SysUserRole;
import com.atguigu.vo.system.AssginRoleVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper,SysRole> implements SysRoleService {

    @Autowired
    private SysUserRoleService sysUserRoleService;

    //1.查询所有角色和当前所属角色
    @Override
    public Map<String, Object> findRoleDataByUserId(Long userId) {
        //1.查询出所有角色  返回List集合
        List<SysRole> allSysRoleList = baseMapper.selectList(null);
        //2.根据用户ID获取角色的ID
        //从查询出所有角色中获取角色ID
        LambdaQueryWrapper<SysUserRole> lqwUserRole = new LambdaQueryWrapper<>();
        lqwUserRole.eq(SysUserRole::getUserId,userId);
        List<SysUserRole> sysUserRoleList = sysUserRoleService.list(lqwUserRole);

        //该用户下面所有角色的id值
        List<Long> roleIdList = sysUserRoleList.stream()
                .map(item -> item.getRoleId()).collect(Collectors.toList());


        //3.查出来的userRole的id值和 所有角色的id值比对，存在则保存到新的sysRoleList集合中
        List<SysRole> sysRoleList = new ArrayList<>();
        allSysRoleList.stream().forEach(item ->{
            if(roleIdList.contains(item.getId())){
                sysRoleList.add(item);
            }
        });

        //4.封装数据
        HashMap<String, Object> roleMap = new HashMap<>();
        roleMap.put("assginRoleList", sysRoleList);//已经存在的userRole集合
        roleMap.put("allRolesList",allSysRoleList);//所有的userRole集合
        return roleMap;
    }



    //2.为用户分配角色
    @Override
    public void doAssign(AssginRoleVo assginRoleVo) {
        //1.根据userId删除sys_role_user表的数据
        LambdaQueryWrapper<SysUserRole> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysUserRole::getUserId,assginRoleVo.getUserId());
        sysUserRoleService.remove(lqw);


        //2.根据assginRoleVo中的RoleList重新分配
        List<Long> roleIdList = assginRoleVo.getRoleIdList();
        List<SysUserRole> sysUserRoleList = new ArrayList<>();

        roleIdList.stream().forEach( item -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(assginRoleVo.getUserId());//需要保存角色的userid
            sysUserRole.setRoleId(item);//保存的roleId的值
            //保存信息
            sysUserRoleList.add(sysUserRole);
        });

        //给中间表批量插入数据
        sysUserRoleService.saveBatch(sysUserRoleList);
    }
}
